# -*- coding: utf-8 -*-
"""
高德步行路径规划 API 封装
输入：起点和终点 [lat, lon] (GCJ02)
输出：路径点 [[lat1, lon1], [lat2, lon2], ...] (GCJ02)
"""

import json
from urllib.request import urlopen


class GaodePlanner:
    def __init__(self, api_key):
        """
        初始化高德 API 调用器
        :param api_key: 高德开放平台申请的 key
        """
        self.api_key = api_key
        self.base_url = "http://restapi.amap.com/v3/direction/walking?"

    @staticmethod
    def _pathstr_to_pathlist(path_str):
        """
        将 polyline 字符串 "lon1,lat1;lon2,lat2" 转换为 [[lat1, lon1], [lat2, lon2], ...]
        注意：这里输出的是 [lat, lon] 顺序，更符合常用习惯
        """
        path_list = []
        for point in path_str.split(";"):
            lon, lat = point.split(",")
            path_list.append([float(lat), float(lon)])
        return path_list

    def get_path(self, origin_point, destination_point, debug=False):
        """
        获取步行路径
        :param origin_point: 起点 [lat, lon] (GCJ02)
        :param destination_point: 终点 [lat, lon] (GCJ02)
        :param debug: 是否打印调试信息
        :return: 路径点 [[lat, lon], ...] (GCJ02)
        """
        # 拼接 URL，注意高德 API 要求顺序为 "lon,lat"
        origin = f"origin={origin_point[1]},{origin_point[0]}"
        destination = f"&destination={destination_point[1]},{destination_point[0]}"
        url = self.base_url + origin + destination + f"&key={self.api_key}"

        if debug:
            print(f"[GaodePlanner] 请求 URL: {url}")

        try:
            res = urlopen(url, timeout=5)
            data = res.read()
            res.close()
            result = json.loads(data)
        except Exception as e:
            print(f"[GaodePlanner] 请求失败: {e}")
            return []

        if result.get("status") != "1":
            print(f"[GaodePlanner] API 调用失败, info={result.get('info', '未知错误')}")
            return []

        # 提取路径点
        path_result = []
        steps = result["route"]["paths"][0]["steps"]
        for idx, step in enumerate(steps):
            step_path = self._pathstr_to_pathlist(step["polyline"])
            if idx == 0:
                path_result.extend(step_path)
            else:
                path_result.extend(step_path[1:])  # 去掉重复点

        if debug:
            print(f"[GaodePlanner] 共生成 {len(path_result)} 个路径点")

        return path_result


# ---------------- 示例用法 ----------------
if __name__ == "__main__":
    key = "f4cb8aadaa299f5d605fa8ecd641bbaa"
    planner = GaodePlanner(api_key=key)

    # GCJ02 坐标（lat, lon）
    origin = [30.262117, 120.123313]
    dest = [30.262897, 120.120773]

    path = planner.get_path(origin, dest, debug=True)
    print("路径点:", path[:5], "...")
